package com.itheima.service;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.POJO.Permission;
import com.itheima.POJO.Role;
import com.itheima.POJO.User;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

@Component
public class SpringSecurityUserService implements UserDetailsService {

    //使用dubbo通过网诺 远程调用服务提供方获得数据库中的用户信息
    @Reference
    private UserService userService;

    //根据用户名查询数据库 获得用户信息
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User userByusername = userService.findUserByusername(username);
        if (userByusername == null){
            //说明用户名不存在
            return null;
        }
        List<GrantedAuthority> list = new ArrayList<>();
        //动态为用户授权
        Set<Role> roles = userByusername.getRoles();
        //遍历角色集合为用户授予角色
        for (Role role : roles) {
                list.add(new SimpleGrantedAuthority(role.getKeyword()));
            Set<Permission> permissions = role.getPermissions();
            for (Permission permission : permissions) {
                //遍历权限集合 为用户授权权限
                list.add(new SimpleGrantedAuthority(permission.getKeyword()));
            }
        }
        // 用户名 密码 和 list(角色和权限)
        return new org.springframework.security.core.userdetails.User(username,userByusername.getPassword(),list);
    }
}
